<!--
 * @Author: huangtianyang 916072572@qq.com
 * @Date: 2023-11-07 16:24:52
 * @LastEditors: huangtianyang
 * @LastEditTime: 2024-01-29 11:26:31
 * @FilePath: \cxl-driving-training\src\components\searchTrainSiteName.vue
-->
<template>
    <el-select
        v-model="name"
        :placeholder="placeholderText"
        clearable
        filterable
        remote
        reserve-keyword
        :disabled="disabled"
        :remote-method="remoteMethod"
        :loading="loading"
        @change="onSelectSite"
    >
        <el-option
            v-for="itemOption in siteOptions"
            :key="itemOption.id"
            :label="itemOption.name"
            :value="itemOption.id"
        />
    </el-select>
</template>
<script setup lang="ts">
import { reactive, ref, watchEffect, onMounted } from 'vue'
import { siteSearchSelete } from '@/apis/trainSite'

//监听父级传递的参数 siteCategory场地类别（2.科目二；3.科目三）
const props = defineProps(['data', 'placeholder', 'siteCategory'])
//注册父组件回调
const emits = defineEmits(['change'])
//默认的场地名称
const name = ref('')
//搜索时显示的loading
const loading = ref(false)
//搜索结果
const siteOptions: any[] = reactive([])
//是否可输入
const disabled = ref(false)
//搜索框宽度
const width = ref('100%')
const placeholderText = ref('请输入场地名称称选择')

watchEffect(() => {
    disabled.value = props.data.disabled
    name.value = props.data.name
    width.value = props.data.width
    if (props.placeholder) {
        placeholderText.value = props.placeholder
    }
    //当情况输入框内容时，列表选项也清空
    if (name.value == '') {
        siteOptions.length = 0
    }
})

/**
 * 监听用户输入的场地名称，搜索
 * @param query
 */
const remoteMethod = (query: string) => {
    if (query) {
        loading.value = true
        getSiteList(query, () => {
            loading.value = false
        })
    }
}

/**
 * 获取公司
 * @param name
 * @param callback
 */
const getSiteList = (name = '', callback = () => {}) => {
    siteSearchSelete({ current: 1, size: 20, name: name, siteCategory: Number(props.siteCategory) }).then(res => {
        siteOptions.length = 0
        res.data.result.records.map((item: any) => {
            siteOptions.push(item)
        })
        callback()
    })
}

/**
 * 监听选择的公司
 * @param res
 */
const onSelectSite = (res: any) => {
    console.log(res, siteOptions, name)
    const result = siteOptions.find((item: any, index: number) => {
        return item.id == res
    })
    emits('change', result)
}

onMounted(() => {
    getSiteList()
})
</script>
